package com.jiao.datasource.proxy;

import com.jiao.datasource.listener.ConnectionListener;
import com.jiao.datasource.listener.ListenerExce;

import javax.sql.DataSource;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.List;

/**
 * @Author: vincent.jiao
 * @Date: 2021/4/16
 */

public class DataSourceProxy implements InvocationHandler {
    public DataSource dataSource;

    public DataSourceProxy (DataSource dataSource){
        this.dataSource = dataSource;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        Object value = method.invoke(dataSource, args);

        if ("getConnection".equalsIgnoreCase(methodName)) {
            value = connectionProxy((Connection) value);
        }

        return value;
    }

    /**
     * 代理连接
     * @return
     */
    private Connection connectionProxy(Connection connectionObj) {
        Connection proxyConn = null;

        if(connectionObj != null){
            InvocationHandler connProxyHandler = new ConnectionProxy(connectionObj);
            proxyConn = (Connection) Proxy.newProxyInstance(connectionObj.getClass().getClassLoader(),
                    new Class[]{Connection.class}, connProxyHandler);

            ListenerExce.open(connectionObj);       //通知链接打开
        }

        return proxyConn;
    }
}
